package com.hk.web.controller.api.frontend;

import com.hk.commons.JsonResult;
import com.hk.commons.ProcessAPI;
import com.hk.commons.ResultCode;
import com.hk.web.controller.Routes;
import com.hk.web.domain.entity.AppGestureCipher;
import com.hk.web.domain.entity.User;
import com.hk.web.domain.lifeCycle.repository.AppGestureCipherRepository;
import com.hk.web.domain.lifeCycle.repository.UserRepository;
import com.hk.web.dto.gesturecipher.*;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.Date;

/**
 * App应用手势密码
 * @author 会飞的狼 on 2018/1/5.
 */

@Api(value = "APP手势密码-移动APP接口", description = "APP手势密码-移动APP接口")
@RestController
public class AppGestureCipherController {

    private Logger logger = LoggerFactory.getLogger(AppGestureCipherController.class);

    @Autowired
    private UserRepository userRepo;

    @Autowired
    private AppGestureCipherRepository gestureCipherRepo;

    @ApiOperation(value = "用户登录 推送信息", notes = "用户登录 推送信息", produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    @RequestMapping(value = Routes.API_GESTURE_CIPHER_GETPUSHMESSAGE, method = RequestMethod.POST, produces = "application/json;charset=UTF-8")
    @ResponseBody
    public JsonResult<GetPushMessageRes> getPushMessage(HttpServletRequest request, @RequestBody GetPushMessageReq getPushMessageReq) {
        logger.info("/getPushMessage----->登录名:{}, 应用类型:{}", getPushMessageReq.getLoginName(), getPushMessageReq.getAppType());

        ProcessAPI api = (jsonResult, validate) -> {
            validate.check("loginName", getPushMessageReq.getLoginName());
            validate.check("appType", getPushMessageReq.getAppType());

            GetPushMessageRes getPushMessageRes = new GetPushMessageRes();

            //1、查SysUser表是否存在该用户
            User userName = userRepo.findByName(getPushMessageReq.getLoginName().trim());

            AppGestureCipher gestureCipherUser = gestureCipherRepo.findByLoginNameAndAppType(getPushMessageReq.getLoginName().trim(), Integer.parseInt(getPushMessageReq.getAppType()));

            //2、把数据移过AppGestureCipher表
            if ((userName != null) && (gestureCipherUser == null)) {
                //新建表
                AppGestureCipher appGestureCipher = new AppGestureCipher();
                appGestureCipher.setAppType(Integer.parseInt(getPushMessageReq.getAppType()));
                appGestureCipher.setLoginName(getPushMessageReq.getLoginName().trim());
                gestureCipherRepo.save(appGestureCipher);

                //修改状状为0
                AppGestureCipher exisGestureCipherUser = gestureCipherRepo.findByLoginNameAndAppType(getPushMessageReq.getLoginName().trim(), Integer.parseInt(getPushMessageReq.getAppType()));
                exisGestureCipherUser.setLoginPushMessage(0);
                exisGestureCipherUser.setLastUpdated(new Date());
                gestureCipherRepo.save(exisGestureCipherUser);

                getPushMessageRes.setLoginPushMessage(1);
                getPushMessageRes.setLoginName(exisGestureCipherUser.getLoginName());

                jsonResult.result = getPushMessageRes;
                jsonResult.resultCode = ResultCode.SUCC.getCode();
                jsonResult.msg = ResultCode.SUCC.getMsg();
            }else {
                AppGestureCipher exisGestureCipherUser = gestureCipherRepo.findByLoginNameAndAppType(getPushMessageReq.getLoginName().trim(), Integer.parseInt(getPushMessageReq.getAppType()));
                getPushMessageRes.setLoginPushMessage(exisGestureCipherUser.getLoginPushMessage());
                getPushMessageRes.setLoginName(getPushMessageReq.getLoginName());
                jsonResult.result = getPushMessageRes;
                jsonResult.resultCode = ResultCode.SUCC.getCode();
                jsonResult.msg = ResultCode.SUCC.getMsg();
            }


            /*AppGestureCipher exisGestureCipherUser = gestureCipherRepo.findByLoginNameAndAppType(getPushMessageReq.getLoginName().trim(), Integer.parseInt(getPushMessageReq.getAppType()));

            getPushMessageRes.setLoginName(exisGestureCipherUser.getLoginName());
            getPushMessageRes.setLoginPushMessage(exisGestureCipherUser.getLoginPushMessage());

            if (!exisGestureCipherUser.getLoginPushMessage().equals(0)) {
                //修改loginPushMessage的值
                AppGestureCipher appGestureCipher = new AppGestureCipher();
                appGestureCipher.setId(exisGestureCipherUser.getId());
                appGestureCipher.setAppType(exisGestureCipherUser.getAppType());
                appGestureCipher.setLoginName(exisGestureCipherUser.getLoginName());
                appGestureCipher.setGestureCipher(exisGestureCipherUser.getGestureCipher());
                appGestureCipher.setLoginPushMessage(0);
                appGestureCipher.setDateCreated(exisGestureCipherUser.getDateCreated());
                gestureCipherRepo.save(appGestureCipher);

                getPushMessageRes.setLoginName(appGestureCipher.getLoginName());
                getPushMessageRes.setLoginPushMessage(appGestureCipher.getLoginPushMessage());
            }

            jsonResult.result = getPushMessageRes;
            jsonResult.resultCode = ResultCode.SUCC.getCode();
            jsonResult.msg = ResultCode.SUCC.getMsg();
            return;
            */
        };

        return api.process(request);
    }


    @ApiOperation(value = "查询手势密码状态及已经保存的手势密码", notes = "查询手势密码状态及已经保存的手势密码", produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    @RequestMapping(value = Routes.API_GESTURE_CIPHER_GETCIPHERSTATE, method = RequestMethod.GET)
    @ResponseBody
    public JsonResult<GetCipherStateRes> getCipherState(HttpServletRequest request, @RequestParam("loginName") String loginName, @RequestParam("appType") String appType) {
        logger.info("返回手势密码状态：/getCipherState----->登录名:{}, 应用APP类型{}", loginName, appType);
        ProcessAPI api = (jsonResult, validate) -> {
            validate.check("loginName", loginName);
            validate.check("appType", appType);

            GetCipherStateRes getCipherStateRes = new GetCipherStateRes();
            AppGestureCipher gestureCipherUser = gestureCipherRepo.findByLoginNameAndAppType(loginName.trim(), Integer.parseInt(appType));
            if(gestureCipherUser == null) {
                jsonResult.result = "用户空";
                jsonResult.resultCode = ResultCode.FAILED.getCode();
                jsonResult.msg = ResultCode.FAILED.getMsg();
                return ;
            }
            //手势密码的值
            String gestureCipher = gestureCipherUser.getGestureCipher();
            Boolean gestureCipherState = gestureCipherUser.getGestureCipherState();

            getCipherStateRes.setCipherState(gestureCipherState);
            getCipherStateRes.setModifyCipher(false);
            getCipherStateRes.setGestureCipher(gestureCipher);

            //开启状态 返回修改手势密码字段
            if((gestureCipherState.equals(true)) && (!StringUtils.isBlank(gestureCipher))) {
                getCipherStateRes.setCipherState(gestureCipherState);
                getCipherStateRes.setModifyCipher(true);
                getCipherStateRes.setGestureCipher(gestureCipher);
            }

            jsonResult.result = getCipherStateRes;
            jsonResult.resultCode = ResultCode.SUCC.getCode();
            jsonResult.msg = ResultCode.SUCC.getMsg();
            return ;

        };

        return api.process(request);
    }

    @ApiOperation(value = "保存手势密码", notes = "保存手势密码", produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    @RequestMapping(value = Routes.API_GESTURE_CIPHER_SAVEGESTURECIPHER, method = RequestMethod.POST, produces = "application/json;charset=UTF-8")
    @ResponseBody
    public JsonResult saveGestureCipher(HttpServletRequest request, @RequestBody SaveGestureCipherReq sgcr) {
        logger.info("保存手势密码 /saveGestureCipher----->登录名:{}, 应用类型:{},手势密码：{}", sgcr.getLoginName(), sgcr.getAppType(), sgcr.getGestureCipher());

        ProcessAPI api = (jsonResult, validate) -> {
            validate.check("loginName", sgcr.getLoginName());
            validate.check("appType", sgcr.getAppType());
            validate.check("gestureCipher", sgcr.getGestureCipher());

            AppGestureCipher gestureCipherUser = gestureCipherRepo.findByLoginNameAndAppType(sgcr.getLoginName(), Integer.parseInt(sgcr.getAppType()));
            if(gestureCipherUser == null) {
                AppGestureCipher appGestureCipher = new AppGestureCipher();
                appGestureCipher.setAppType(Integer.parseInt(sgcr.getAppType()));
                appGestureCipher.setLoginName(sgcr.getLoginName().trim());
                appGestureCipher.setLoginPushMessage(0);
                gestureCipherRepo.save(appGestureCipher);
            }

            AppGestureCipher exisGestureCipherUser = gestureCipherRepo.findByLoginNameAndAppType(sgcr.getLoginName().trim(), Integer.parseInt(sgcr.getAppType()));
            exisGestureCipherUser.setGestureCipher(sgcr.getGestureCipher());
            exisGestureCipherUser.setGestureCipherState(true);
            exisGestureCipherUser.setLastUpdated(new Date());

            gestureCipherRepo.save(exisGestureCipherUser);

            jsonResult.result = "保存手势密码成功";
            jsonResult.resultCode = ResultCode.SUCC.getCode();
            jsonResult.msg = ResultCode.SUCC.getMsg();
            return ;

        };

        return api.process(request);
    }


    /**
     * 修改手势密码
     * @param request
     * @param sgcr
     * @return
     */
    @ApiOperation(value = "修改手势密码", notes = "修改手势密码", produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    @RequestMapping(value = Routes.API_GESTURE_CIPHER_MODIFYGESTURECIPHER, method = RequestMethod.POST, produces = "application/json;charset=UTF-8")
    @ResponseBody
    public JsonResult modifyGestureCipher(HttpServletRequest request, @RequestBody SaveGestureCipherReq sgcr) {
        logger.info("修改手势密码 /modifyGestureCipher----->登录名:{}, 应用类型:{},手势密码：{}", sgcr.getLoginName(), sgcr.getAppType(), sgcr.getGestureCipher());
        ProcessAPI api = (jsonResult, validate) -> {
            validate.check("loginName", sgcr.getLoginName());
            validate.check("appType", sgcr.getAppType());
            validate.check("gestureCipher", sgcr.getGestureCipher());

            AppGestureCipher gestureCipherUser = gestureCipherRepo.findByLoginNameAndAppType(sgcr.getLoginName(), Integer.parseInt(sgcr.getAppType()));

            if(StringUtils.isBlank(gestureCipherUser.getGestureCipher()) || gestureCipherUser == null) {
                jsonResult.result = "该用户还没有手势密码";
                jsonResult.resultCode = ResultCode.FAILED.getCode();
                jsonResult.msg = ResultCode.FAILED.getMsg();
                return;
            }

            gestureCipherUser.setGestureCipher(sgcr.getGestureCipher());
            gestureCipherUser.setGestureCipherState(true);
            gestureCipherUser.setLastUpdated(new Date());

            gestureCipherRepo.save(gestureCipherUser);

            jsonResult.result = "修改手势密码成功";
            jsonResult.resultCode = ResultCode.SUCC.getCode();
            jsonResult.msg = ResultCode.SUCC.getMsg();
            return;
        };

        return api.process(request);
    }


    /**
     * 开关闭手势密码 切换
     */
    @ApiOperation(value = "手势密码开关 切换", notes = "手势密码开关 切换", produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    @RequestMapping(value = Routes.API_GESTURE_CIPHER_SWITCHGESTURECIPHERSTATE, method = RequestMethod.POST, produces = "application/json;charset=UTF-8")
    @ResponseBody
    public JsonResult<SwitchGestureCipherStateRes> switchGestureCipherState(HttpServletRequest request, @RequestBody SwitchGestureCipherReq sgcr) {
        logger.info("开关手势密码切换 /switchGestureCipherState----->登录名:{}, 应用类型:{},切换状态：{}", sgcr.getLoginName(), sgcr.getAppType(), sgcr.getType());

        ProcessAPI api = (jsonResult, validate) -> {
            validate.check("loginName", sgcr.getLoginName());
            validate.check("appType", sgcr.getAppType());
            validate.check("type", sgcr.getType());

            SwitchGestureCipherStateRes switchGestureCipherStateRes = new SwitchGestureCipherStateRes();
            AppGestureCipher gestureCipherUser = gestureCipherRepo.findByLoginNameAndAppType(sgcr.getLoginName(), Integer.parseInt(sgcr.getAppType()));
            if(gestureCipherUser == null) {
                jsonResult.result = "无该用户";
                jsonResult.resultCode = ResultCode.FAILED.getCode();
                jsonResult.msg = ResultCode.FAILED.getMsg();
                return;
            }

            gestureCipherUser.setGestureCipherState(sgcr.getType());
            gestureCipherUser.setLastUpdated(new Date());
            //TODO 手势密码关闭后清空密码？
            gestureCipherUser.setGestureCipher(null);
            gestureCipherRepo.save(gestureCipherUser);

            switchGestureCipherStateRes.setLoginName(gestureCipherUser.getLoginName());
            switchGestureCipherStateRes.setAppType(gestureCipherUser.getAppType());


            switchGestureCipherStateRes.setGestureCipherState(gestureCipherUser.getGestureCipherState());

            jsonResult.result = switchGestureCipherStateRes;
            jsonResult.resultCode = ResultCode.SUCC.getCode();
            jsonResult.msg = ResultCode.SUCC.getMsg();
            return;
        };

        return api.process(request);
    }


    /**
     * 清空手势密码接口
     */
    @ApiOperation(value = "清空手势密码接口", notes = "清空手势密码接口", produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    @RequestMapping(value = Routes.API_GESTURE_CIPHER_CLEANGESTURECIPHER, method = RequestMethod.POST, produces = "application/json;charset=UTF-8")
    @ResponseBody
    public JsonResult cleanGestureCipher(HttpServletRequest request, @RequestBody GetPushMessageReq gpmr) {
        logger.info("清空手势密码 /cleanGestureCipher----->登录名:{}, 应用类型:{},手势密码：{}", gpmr.getLoginName(), gpmr.getAppType());
        ProcessAPI api = (jsonResult, validate) -> {
            validate.check("loginName", gpmr.getLoginName());
            validate.check("appType", gpmr.getAppType());

            AppGestureCipher gestureCipherUser = gestureCipherRepo.findByLoginNameAndAppType(gpmr.getLoginName(), Integer.parseInt(gpmr.getAppType()));
            if(StringUtils.isBlank(gestureCipherUser.getGestureCipher())) {
                jsonResult.result = "该用户无手势密码";
                jsonResult.resultCode = ResultCode.FAILED.getCode();
                jsonResult.msg = ResultCode.FAILED.getMsg();
                return ;
            }

            gestureCipherUser.setGestureCipher(null);
            gestureCipherUser.setLastUpdated(new Date());
            gestureCipherRepo.save(gestureCipherUser);

            jsonResult.result = "清空手势密码成功";
            jsonResult.resultCode = ResultCode.SUCC.getCode();
            jsonResult.msg = ResultCode.SUCC.getMsg();
            return ;
        };

        return api.process(request);
    }


    /**
     * 忘记手势密码，登录密码校验
     */
    @ApiOperation(value = "忘记手势密码，使用登录密码校验重新设置", notes = "忘记手势密码，使用登录密码校验重新设置", produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    @RequestMapping(value = Routes.API_GESTURE_CIPHER_FORGETGESTURECIPHER, method = RequestMethod.POST, produces = "application/json;charset=UTF-8")
    @ResponseBody
    public JsonResult<ForgetGestureCipherRes> forgetGestureCipher(HttpServletRequest request, @RequestBody ForGetGestureCipherReq fggcr) {
        logger.info("忘记手势密码,登录密码重新验证设置 /forgetGestureCipher----->登录名:{},登录密码：{}", fggcr.getLoginName(), fggcr.getPassword());

        ProcessAPI api = (jsonResult, validate) -> {
            validate.check("loginName", fggcr.getLoginName());
            validate.check("password", fggcr.getPassword());

            boolean isAuthenticationSuccess = false;
            ForgetGestureCipherRes forgetGestureCipherRes = new ForgetGestureCipherRes();
            User userName = userRepo.findByName(fggcr.getLoginName().trim());

            AppGestureCipher gestureCipherUser = gestureCipherRepo.findByLoginNameAndAppType(fggcr.getLoginName(), Integer.parseInt(fggcr.getAppType()));

            if (userName == null) {
                logger.info("login 此用户不存在 name = {} ",fggcr.getLoginName());
                jsonResult.result = "此用户不存在";
                jsonResult.resultCode = ResultCode.USER_NOT_EXIST.getCode();
                jsonResult.msg = ResultCode.USER_NOT_EXIST.getMsg();
                return ;
            }

            if (userName.getPwd().equalsIgnoreCase(fggcr.getPassword())) {
                isAuthenticationSuccess = true;
                forgetGestureCipherRes.setAuthentication(isAuthenticationSuccess);
                forgetGestureCipherRes.setLoginName(fggcr.getLoginName());

                //备注 后台处理 修改登录密码 一、清空手势密码 二、关闭手密码
                gestureCipherUser.setGestureCipher(null);
                gestureCipherUser.setGestureCipherState(false);
                gestureCipherRepo.save(gestureCipherUser);
            } else {
                logger.info("login 账号或密码错误 name={}",fggcr.getLoginName());
                isAuthenticationSuccess = false;
                forgetGestureCipherRes.setAuthentication(isAuthenticationSuccess);
                forgetGestureCipherRes.setLoginName(fggcr.getLoginName());
                jsonResult.result = forgetGestureCipherRes;
                jsonResult.resultCode = ResultCode.PASSWORD_ERROR.getCode();
                jsonResult.msg = ResultCode.PASSWORD_ERROR.getMsg();
                return ;
            }

            jsonResult.result = forgetGestureCipherRes;
            jsonResult.resultCode = ResultCode.SUCC.getCode();
            jsonResult.msg = ResultCode.SUCC.getMsg();
            return ;
        };

        return api.process(request);
    }

}
